using System;
using System.Collections.Generic;
using System.Linq;
using Kotonoha.Objects;
using Kotonoha.Server.Core.Utils;
using Kotonoha.Server.Db.Dao;
using Kotonoha.Server.Objects.Model;
using Kotonoha.Server.Dictionaries;
using Kotonoha.Server.Examples;
using Kotonoha.Server.Extensions;
using Kotonoha.Server.Settings;
using Word=Kotonoha.Server.Objects.Model.Word;

namespace Kotonoha.Server.Model {
    public class WordFiller {

        public bool findAndFill(string entered, out Word w) {
            IList<WordEntry> entries = new DictDao(HibernateUtil.Instance.Session).findWordByWriting(entered);
            if (entries.IsEmpty()) {
                w = null;
                return false;
            }
            var entry = entries.First();
            return fill(entry, entered, out w);
        }

        public bool fill(WordEntry entry, string entered, out Word w) {
            w = new Word();
            w.Writing = entered;
            w.Translations = entry.Meanings.Where(m => !m.IsEmpty()).Select(m => selector(m)).ToArray();
            w.Reading = selector(entry.Readings);
            fillCommonInWord(w);

            return true;
        }

        internal static void fillCommonInWord(Word w) {
            w.AddedDate = DateTime.Now;
            w.Repetition = new TimedVariable(0.1, -1) {Min = 0.1};
            w.Examples = convert(new DictDao(HibernateUtil.Instance.Session).findExamples(w.Writing, 5));
        }

        private static Example[] convert(IEnumerable<ExampleEntry> list) {
            return list.Select(ex => new Example {Content = ex.Content, Translation = ex.Translation}).ToArray();
        }

        private static string selector(IEnumerable<string> m) {
            return m.Aggregate((s1, s2) => string.Format("{0}, {1}", s1, s2));
        }
    }
}